import os.path
import fimero.core.util.LogKit as LogKit
import fimero.core.disk.PathKit as PathKit
import fimero.core.disk.TextFileKit as TextFileKit
from mako.template import Template
from mako.lookup import TemplateLookup
from mako.runtime import Context
from StringIO import StringIO

LOGGER = LogKit.get_logger(__name__)

# need absolute path to skel folder
__SKEL_PARENT_FOLDER__ = PathKit.parent_folder(__file__)
__SKEL_FOLDER__ = '/'.join([__SKEL_PARENT_FOLDER__, 'skel'])
__SKEL_LOOKUP__ = TemplateLookup(directories=[__SKEL_FOLDER__], \
                                 module_directory='/tmp/mako_cache')

def lookup_template(template_name):
    """
    Returns an template instance for the specified template file name.
    """
    return __SKEL_LOOKUP__.get_template(template_name)
    
def render_template(template_name, args, buf=StringIO()):
    """
    render the template with the specified file name.
    
    args: a dictionary of key:value pairs for template
    buf (optional) : buffer to hold result
    """
    ctx = Context(buf, **args)
    template = lookup_template(template_name)
    template.render_context(ctx)    
    return buf

def write_template(template_name, args, path):
    """Writes the result of the template render to path, making a bak file
    if path already exists."""
    buffer = render_template(template_name, args)
    outfile = TextFileKit.make(path)
    
    if outfile.exists():
        PathKit.rename_to_bak(outfile.get_path())
        
    outfile.write_text(buffer.getvalue())
    
 